package cn.cocho.android.mc.util;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import cn.cocho.android.mc.log.LoggerUtils;

public class AppUtils {

	/**
	 * 获取软件的版本名称
	 * 
	 * @param context
	 * @param defaultName
	 * @return
	 */
	public static String getVersionName(Context context) {
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (NameNotFoundException e) {
			LoggerUtils.error(e);
			return "";
		}
	}

	/**
	 * 获取版本号(内部识别号)
	 * 
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			LoggerUtils.error(e);
			return 0;
		}
	}

	/**
	 * 获得当前应用的包名
	 * 
	 * @param context
	 * @return
	 */
	public static String getPackageName(Context context) {
		String result = "";
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			result = info.packageName;
		} catch (NameNotFoundException e) {
			LoggerUtils.error(e);
		}
		return result;
	}

	/**
	 * 判断当前应用程序处于前台还是后台<br>
	 * 需要配置权限<uses-permission android:name="android.permission.GET_TASKS" />
	 * 
	 */
	public static boolean isApplicationBroughtToBackground(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 退出当前程序
	 */
	public static void exitApp() {
		android.os.Process.killProcess(android.os.Process.myPid()); // 获取PID
		System.exit(0); // 常规java、c#的标准退出法，返回值为0代表正常退出
	}
}
